/*******************************************************************************
 * Copyright (c) 2011 squid.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 * 
 * Contributors:
 *     squid - initial API and implementation
 ******************************************************************************/
package com.google.code.cubeirc.ui;

import java.util.ArrayList;
import java.util.Iterator;

import lombok.Getter;

import org.apache.log4j.Level;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.wb.swt.SWTResourceManager;

import com.google.code.cubeirc.base.BaseTab;
import com.google.code.cubeirc.common.ApplicationInfo;
import com.google.code.cubeirc.config.Configuration;
import com.google.code.cubeirc.config.ConnectionSettings;



public class ServerForm extends BaseTab {
	private Group grpServerInfo;
	private Button btnAdd;
	private Button btnRemove;
	private Label lblName;
	private Text edtName;
	private Label lblIpAddress;
	private Text edtIPAddress;
	private Label lblPort;
	private Text edtPort;
	private Label lblServerPassword;
	private Text edtServerPassword;
	private Button cbSSL;
	private Label lblIdent;
	private Text edtIdent;
	private TableColumn tblclmnConnectionName;
	private TableColumn tblclmnIpAddress;
	private TableColumn tblclmnPort;

	@Getter
	private Table tbServers;
	private Button btnSave;
	private Button btnAddToList;

	public ServerForm(Composite composite, int style, String name) {
		super(composite, style, name);
		jbInit();
	}


	private void jbInit() {
		setLayout(new FormLayout());

		tbServers = new Table(this, SWT.BORDER | SWT.FULL_SELECTION);
		this.tbServers.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent arg0) {
				selectServer();
			}
		});
		FormData fd_tbServers = new FormData();
		fd_tbServers.left = new FormAttachment(0);
		fd_tbServers.right = new FormAttachment(100, -93);
		fd_tbServers.top = new FormAttachment(0);
		fd_tbServers.bottom = new FormAttachment(0, 159);
		tbServers.setLayoutData(fd_tbServers);
		tbServers.setHeaderVisible(true);
		tbServers.setLinesVisible(true);

		this.grpServerInfo = new Group(this, SWT.NONE);
		this.grpServerInfo.setText("Server info");
		this.grpServerInfo.setLayout(new FormLayout());
		FormData fd_grpServerInfo = new FormData();
		fd_grpServerInfo.right = new FormAttachment(tbServers, 0, SWT.RIGHT);
		fd_grpServerInfo.bottom = new FormAttachment(100, -83);
		fd_grpServerInfo.top = new FormAttachment(tbServers, 6);
		fd_grpServerInfo.left = new FormAttachment(0);
		this.grpServerInfo.setLayoutData(fd_grpServerInfo);

		this.lblName = new Label(this.grpServerInfo, SWT.NONE);
		FormData fd_lblName = new FormData();
		fd_lblName.top = new FormAttachment(0, 10);
		fd_lblName.left = new FormAttachment(0, 10);
		this.lblName.setLayoutData(fd_lblName);
		this.lblName.setText("Name:");

		this.edtName = new Text(this.grpServerInfo, SWT.BORDER);
		FormData fd_edtName = new FormData();
		fd_edtName.top = new FormAttachment(this.lblName);
		fd_edtName.left = new FormAttachment(this.lblName, 0, SWT.LEFT);
		fd_edtName.right = new FormAttachment(0, 136);
		this.edtName.setLayoutData(fd_edtName);

		this.lblIpAddress = new Label(this.grpServerInfo, SWT.NONE);
		FormData fd_lblIpAddress = new FormData();
		fd_lblIpAddress.top = new FormAttachment(this.edtName, 6);
		fd_lblIpAddress.left = new FormAttachment(this.lblName, 0, SWT.LEFT);
		this.lblIpAddress.setLayoutData(fd_lblIpAddress);
		this.lblIpAddress.setText("IP Address:");

		this.edtIPAddress = new Text(this.grpServerInfo, SWT.BORDER);
		FormData fd_edtIPAddress = new FormData();
		fd_edtIPAddress.top = new FormAttachment(this.lblIpAddress, 6);
		fd_edtIPAddress.right = new FormAttachment(this.edtName, -3, SWT.RIGHT);
		fd_edtIPAddress.left = new FormAttachment(this.lblName, 0, SWT.LEFT);
		this.edtIPAddress.setLayoutData(fd_edtIPAddress);

		this.lblPort = new Label(this.grpServerInfo, SWT.NONE);
		this.lblPort.setText("Port:");
		FormData fd_lblPort = new FormData();
		fd_lblPort.bottom = new FormAttachment(this.lblIpAddress, 0, SWT.BOTTOM);
		fd_lblPort.left = new FormAttachment(this.lblIpAddress, 74);
		this.lblPort.setLayoutData(fd_lblPort);

		this.edtPort = new Text(this.grpServerInfo, SWT.BORDER);
		FormData fd_edtPort = new FormData();
		fd_edtPort.top = new FormAttachment(this.edtIPAddress, 0, SWT.TOP);
		fd_edtPort.left = new FormAttachment(this.edtIPAddress, 6);
		this.edtPort.setLayoutData(fd_edtPort);

		this.lblServerPassword = new Label(this.grpServerInfo, SWT.NONE);
		FormData fd_lblServerPassword = new FormData();
		fd_lblServerPassword.bottom = new FormAttachment(this.lblName, 0, SWT.BOTTOM);
		fd_lblServerPassword.left = new FormAttachment(this.lblName, 182);
		this.lblServerPassword.setLayoutData(fd_lblServerPassword);
		this.lblServerPassword.setText("Server password:");

		this.edtServerPassword = new Text(this.grpServerInfo, SWT.BORDER);
		FormData fd_edtServerPassword = new FormData();
		fd_edtServerPassword.top = new FormAttachment(this.edtName, 0, SWT.TOP);
		fd_edtServerPassword.right = new FormAttachment(this.lblPort, 168, SWT.RIGHT);
		fd_edtServerPassword.left = new FormAttachment(this.lblServerPassword, 0, SWT.LEFT);
		this.edtServerPassword.setLayoutData(fd_edtServerPassword);

		this.cbSSL = new Button(this.grpServerInfo, SWT.CHECK);
		FormData fd_cbSSL = new FormData();
		fd_cbSSL.top = new FormAttachment(this.edtIPAddress, 0, SWT.TOP);
		fd_cbSSL.left = new FormAttachment(this.lblServerPassword, 0, SWT.LEFT);
		this.cbSSL.setLayoutData(fd_cbSSL);
		this.cbSSL.setText("Use SSL");

		this.lblIdent = new Label(this.grpServerInfo, SWT.NONE);
		FormData fd_lblIdent = new FormData();
		fd_lblIdent.top = new FormAttachment(this.lblName, 0, SWT.TOP);
		fd_lblIdent.left = new FormAttachment(this.lblServerPassword, 53);
		this.lblIdent.setLayoutData(fd_lblIdent);
		this.lblIdent.setText("IDENT");

		this.edtIdent = new Text(this.grpServerInfo, SWT.BORDER);
		FormData fd_edtIdent = new FormData();
		fd_edtIdent.top = new FormAttachment(this.edtName, 0, SWT.TOP);
		fd_edtIdent.left = new FormAttachment(this.edtServerPassword, 30);
		this.edtIdent.setLayoutData(fd_edtIdent);

		this.btnAddToList = new Button(this.grpServerInfo, SWT.NONE);
		this.btnAddToList.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent arg0) {
				addToTable(new ConnectionSettings(edtName.getText(), edtIPAddress.getText(),edtPort.getText(), edtServerPassword.getText(), cbSSL.getSelection(), edtIdent.getText()));
			}
		});
		this.btnAddToList.setImage(SWTResourceManager.getImage(ServerForm.class, "/com/google/code/cubeirc/resources/img_add.png"));
		FormData fd_btnAddToList = new FormData();
		fd_btnAddToList.top = new FormAttachment(this.edtIPAddress, 21);
		fd_btnAddToList.left = new FormAttachment(this.lblName, 0, SWT.LEFT);
		this.btnAddToList.setLayoutData(fd_btnAddToList);
		this.btnAddToList.setText("Add to list");

		this.btnAdd = new Button(this, SWT.NONE);
		this.btnAdd.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent arg0) {
				newServer();
			}
		});
		this.btnAdd.setImage(SWTResourceManager.getImage(ServerForm.class, "/com/google/code/cubeirc/resources/img_add.png"));
		FormData fd_btnAdd = new FormData();
		fd_btnAdd.right = new FormAttachment(tbServers, 83, SWT.RIGHT);
		fd_btnAdd.top = new FormAttachment(0);
		fd_btnAdd.left = new FormAttachment(tbServers, 6);
		fd_btnAdd.bottom = new FormAttachment(0, 26);
		this.btnAdd.setLayoutData(fd_btnAdd);
		this.btnAdd.setText("Add");

		this.btnRemove = new Button(this, SWT.NONE);
		this.btnRemove.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent arg0) {
				removeServer();
			}
		});
		this.btnRemove.setImage(SWTResourceManager.getImage(ServerForm.class, "/com/google/code/cubeirc/resources/img_remove.gif"));
		FormData fd_btnRemove = new FormData();
		fd_btnRemove.top = new FormAttachment(this.btnAdd, 6);
		fd_btnRemove.left = new FormAttachment(tbServers, 6);

		this.tblclmnConnectionName = new TableColumn(tbServers, SWT.NONE);
		this.tblclmnConnectionName.setWidth(124);
		this.tblclmnConnectionName.setText("Connection name");

		this.tblclmnIpAddress = new TableColumn(tbServers, SWT.NONE);
		this.tblclmnIpAddress.setWidth(100);
		this.tblclmnIpAddress.setText("IP address");

		this.tblclmnPort = new TableColumn(tbServers, SWT.NONE);
		this.tblclmnPort.setWidth(100);
		this.tblclmnPort.setText("Port");
		this.btnRemove.setLayoutData(fd_btnRemove);
		this.btnRemove.setText("Remove");

	

		this.btnSave = new Button(this, SWT.NONE);
		this.btnSave.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent arg0) {
				saveServers();
			}
		});
		this.btnSave.setImage(SWTResourceManager.getImage(ServerForm.class, "/com/google/code/cubeirc/resources/img_save.png"));
		FormData fd_btnSave = new FormData();
		fd_btnSave.right = new FormAttachment(this.btnAdd, 0, SWT.RIGHT);
		fd_btnSave.top = new FormAttachment(this.btnRemove, 6);
		fd_btnSave.left = new FormAttachment(this.tbServers, 6);
		this.btnSave.setLayoutData(fd_btnSave);
		this.btnSave.setText("Save");
		
		loadServersSettings();
	}

	@Override
	protected void checkSubclass() {
		// Disable the check that prevents subclassing of SWT components
	}

	private void selectServer()
	{
		asyncExec(new Runnable() {

			@Override
			public void run() {
				if (getTbServers().getSelectionIndex() > -1)
				{
					TableItem ti = getTbServers().getItem(getTbServers().getSelectionIndex());
					if (ti.getData() instanceof ConnectionSettings)
					{
						ConnectionSettings cs = (ConnectionSettings) ti.getData();
						addToEdit(cs);
					}
				}
			}
		});
	}
	
	private void removeServer()
	{
		 asyncExec(new Runnable() {
			
			@Override
			public void run() {
				if (getTbServers().getSelectionIndex() > -1)
				{
					getTbServers().remove(getTbServers().getSelectionIndex());
				}
				
			}
		});
		 
		
	}

	private void addToTable(final ConnectionSettings cs)
	{	
		asyncExec(new Runnable() {
			
			@Override
			public void run() {
				
				TableItem tb = new TableItem(getTbServers(), SWT.NORMAL);
				tb.setText(0, cs.getConnectionName());
				tb.setText(1, cs.getServer());
				tb.setText(2, cs.getPort());			
				tb.setData(cs);
				
			}
		});
		
	}
	
	private void addToEdit(final ConnectionSettings cs)
	{
		asyncExec(new Runnable() {
			
			@Override
			public void run() {
				edtName.setText(cs.getConnectionName());
				edtIPAddress.setText(cs.getServer());
				edtIdent.setText(cs.getIdent());
				cbSSL.setSelection(cs.isSsl());
				edtPort.setText(cs.getPort());		
				
			}
		});
		
	}
	private void newServer()
	{
		asyncExec(new Runnable() {

			@Override
			public void run() {
				edtName.setText("");
				edtIPAddress.setText("");
				edtIdent.setText("");
				cbSSL.setSelection(false);
				edtPort.setText("");	
				edtName.setFocus();
			}
		});
	}

	private void saveServers()
	{
		asyncExec(new Runnable() {

			@Override
			public void run() {
				ArrayList<ConnectionSettings> l_cs = new ArrayList<ConnectionSettings>();
				for (int i=0; i<getTbServers().getItems().length; i++)
				{
					if (getTbServers().getItem(i).getData() instanceof ConnectionSettings)
					{
						l_cs.add((ConnectionSettings) getTbServers().getItem(i).getData());
					}
				}

				Configuration.saveCStoFile(ApplicationInfo.CNS_SERVERS, l_cs);
				MessageBox mb = new MessageBox(getShell(), SWT.ICON_INFORMATION | SWT.OK);
				mb.setText(ApplicationInfo.APP_FULL);
				mb.setMessage("Connections saved!");
				mb.open();
				Configuration.loadCSfromFile(ApplicationInfo.CNS_SERVERS);				

			}
		});
	}

	private void loadServersSettings()
	{
		asyncExec( new Runnable() {

			@Override
			public void run() {
				addDebug(Level.DEBUG, "Checking servers file %s", ApplicationInfo.CNS_SERVERS);
				Configuration.loadCSfromFile(ApplicationInfo.CNS_SERVERS);
				if (Configuration.getCurrentCSSettings() != null)
				{

					for (Iterator<ConnectionSettings> it = Configuration.getCurrentCSSettings().iterator(); it.hasNext();)
					{
						ConnectionSettings cs = it.next();

						addToTable(cs);
					}										
				}				
			}
		});


	}
}
